<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>科室管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2c3e50;
            --success-color: #2ecc71;
            --danger-color: #e74c3c;
        }

        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .page-title {
            color: var(--secondary-color);
            font-weight: 600;
            margin-bottom: 1.5rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid var(--primary-color);
        }

        .card-custom {
            border: none;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        }

        .card-header-custom {
            background: linear-gradient(135deg, var(--secondary-color), #34495e);
            color: white;
            border-radius: 10px 10px 0 0 !important;
            padding: 1.25rem 1.5rem;
            font-weight: 600;
        }

        .btn-custom-primary {
            background: linear-gradient(135deg, var(--primary-color), #2980b9);
            border: none;
            border-radius: 6px;
            color: white;
            font-weight: 500;
            padding: 0.5rem 1.25rem;
            transition: all 0.3s ease;
        }

        .btn-custom-primary:hover {
            background: linear-gradient(135deg, #2980b9, var(--primary-color));
            transform: translateY(-1px);
            box-shadow: 0 4px 8px rgba(52, 152, 219, 0.3);
        }

        .btn-custom-outline {
            border: 1px solid #dee2e6;
            border-radius: 6px;
            background: white;
            color: #495057;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn-custom-outline:hover {
            background-color: #f8f9fa;
            border-color: var(--primary-color);
            color: var(--primary-color);
        }

        .table-custom tbody tr:hover {
            background-color: #f8fafc;
        }

        .status-badge {
            padding: 0.3rem 0.6rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 500;
        }

        .status-active {
            background-color: rgba(46, 204, 113, 0.15);
            color: var(--success-color);
        }

        .status-inactive {
            background-color: rgba(231, 76, 60, 0.15);
            color: var(--danger-color);
        }

        .search-box {
            max-width: 300px;
        }

        .action-btn {
            margin: 0 2px;
            padding: 0.25rem 0.5rem;
            font-size: 0.8rem;
        }

        .empty-state {
            text-align: center;
            padding: 3rem 1rem;
            color: #6c757d;
        }

        .empty-state i {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: #dee2e6;
        }

        .form-control-custom {
            border-radius: 6px;
            border: 1px solid #dee2e6;
            padding: 0.5rem 0.75rem;
        }

        .form-control-custom:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(52, 152, 219, 0.25);
        }
    </style>
</head>
<body>
<div class="container-fluid mt-4">
    <!-- 页面标题 -->
    <div class="row mb-4">
        <div class="col">
            <h2 class="page-title"><i class="bi bi-hospital me-2"></i>医院科室管理</h2>
            <p class="text-muted">管理系统内所有医疗科室信息，包括添加、编辑、删除科室</p>
        </div>
    </div>

    <!-- 搜索和操作栏 -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="input-group search-box">
                <input type="text" id="searchInput" class="form-control form-control-custom" placeholder="搜索科室编码、名称或负责人...">
                <button class="btn btn-custom-primary" type="button" id="searchBtn">
                    <i class="bi bi-search me-1"></i> 搜索
                </button>
                <button class="btn btn-outline-secondary" type="button" id="clearSearchBtn" title="清除搜索">
                    <i class="bi bi-x"></i>
                </button>
            </div>
        </div>
        <div class="col-md-6 text-end">
            <button class="btn btn-custom-primary" id="addBtn">
                <i class="bi bi-plus-circle me-1"></i> 新增科室
            </button>
        </div>
    </div>

    <!-- 科室表格 -->
    <div class="card card-custom">
        <div class="card-header card-header-custom">
            <span><i class="bi bi-list-ul me-2"></i>科室列表</span>
            <small class="text-white-50" id="searchResultInfo"></small>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-custom table-hover">
                    <thead>
                    <tr>
                        <th>科室编码</th>
                        <th>科室名称</th>
                        <th>负责人</th>
                        <th>联系电话</th>
                        <th>位置</th>
                        <th>状态</th>
                        <th>排序</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="departmentTable">
                    <!-- 数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>

            <!-- 分页 -->
            <div class="row align-items-center mt-3">
                <div class="col-md-6" id="paginationInfo">
                    显示第 0 到 0 条，共 0 条记录
                </div>
                <div class="col-md-6">
                    <nav>
                        <ul class="pagination justify-content-end" id="pagination">
                            <!-- 分页将通过JavaScript动态生成 -->
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 新增/编辑科室模态框 -->
<div class="modal fade" id="departmentModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle"><i class="bi bi-building me-2"></i>新增科室</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="departmentForm">
                    <input type="hidden" id="id">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="deptCode" class="form-label">科室编码 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control form-control-custom" id="deptCode" required
                                   placeholder="如：INTERNAL、SURGERY等">
                            <div class="form-text" id="codeCheckResult">请输入英文科室编码</div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="deptName" class="form-label">科室名称 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control form-control-custom" id="deptName" required
                                   placeholder="如：内科、外科等">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="deptHead" class="form-label">负责人</label>
                            <input type="text" class="form-control form-control-custom" id="deptHead"
                                   placeholder="请输入负责人姓名">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="deptPhone" class="form-label">联系电话</label>
                            <input type="text" class="form-control form-control-custom" id="deptPhone"
                                   placeholder="如：010-12345678">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="deptLocation" class="form-label">科室位置</label>
                            <input type="text" class="form-control form-control-custom" id="deptLocation"
                                   placeholder="如：门诊楼1层A区">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="status" class="form-label">状态</label>
                            <select class="form-select form-control-custom" id="status">
                                <option value="1">启用</option>
                                <option value="0">停用</option>
                            </select>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="sortOrder" class="form-label">排序号</label>
                            <input type="number" class="form-control form-control-custom" id="sortOrder" value="0" min="0">
                            <div class="form-text">数字越小排序越靠前</div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="deptDescription" class="form-label">科室描述</label>
                        <textarea class="form-control form-control-custom" id="deptDescription" rows="3"
                                  placeholder="请输入科室的详细描述信息..."></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-custom-outline" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-custom-primary" id="saveBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-exclamation-triangle me-2"></i>确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除这个科室吗？此操作不可恢复。</p>
                <p class="text-muted small">删除后该科室将不再显示在科室列表中。</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-custom-outline" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">
                    <i class="bi bi-trash me-1"></i> 确认删除
                </button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // 全局变量
    let currentPage = 1;
    const pageSize = 10;
    let currentKeyword = '';
    let totalRecords = 0;
    let departmentToDelete = null;
    let useMockData = true; // 设置为true使用模拟数据

    // 模拟数据 - 基于您提供的数据库内容
    const mockDepartments = [
        {
            id: 1,
            deptCode: "INTERNAL",
            deptName: "内科",
            deptDescription: "负责内科疾病诊治",
            deptPhone: "010-12345678",
            deptLocation: "门诊楼1层A区",
            deptHead: "张医生",
            status: 1,
            sortOrder: 1,
            createTime: "2025-10-13 18:10:45",
            updateTime: "2025-10-13 18:10:45",
            createBy: "",
            updateBy: "",
            isDeleted: 0
        },
        {
            id: 2,
            deptCode: "SURGERY",
            deptName: "外科",
            deptDescription: "负责外科手术和治疗",
            deptPhone: "010-12345679",
            deptLocation: "门诊楼1层B区",
            deptHead: "李医生",
            status: 1,
            sortOrder: 2,
            createTime: "2025-10-13 18:10:45",
            updateTime: "2025-10-13 18:10:45",
            createBy: "",
            updateBy: "",
            isDeleted: 0
        },
        {
            id: 3,
            deptCode: "PEDIATRICS",
            deptName: "儿科",
            deptDescription: "儿童疾病专科",
            deptPhone: "010-12345680",
            deptLocation: "门诊楼2层A区",
            deptHead: "王医生",
            status: 1,
            sortOrder: 3,
            createTime: "2025-10-13 18:10:45",
            updateTime: "2025-10-13 18:10:45",
            createBy: "",
            updateBy: "",
            isDeleted: 0
        },
        {
            id: 4,
            deptCode: "GYNECOLOGY",
            deptName: "妇科",
            deptDescription: "妇女疾病专科",
            deptPhone: "010-12345681",
            deptLocation: "门诊楼2层B区",
            deptHead: "赵医生",
            status: 1,
            sortOrder: 4,
            createTime: "2025-10-13 18:10:45",
            updateTime: "2025-10-13 18:10:45",
            createBy: "",
            updateBy: "",
            isDeleted: 0
        },
        {
            id: 5,
            deptCode: "EMERGENCY",
            deptName: "急诊科",
            deptDescription: "24小时急诊服务",
            deptPhone: "010-12345682",
            deptLocation: "急诊楼1层",
            deptHead: "刘医生",
            status: 1,
            sortOrder: 5,
            createTime: "2025-10-13 18:10:45",
            updateTime: "2025-10-13 18:10:45",
            createBy: "",
            updateBy: "",
            isDeleted: 0
        }
    ];

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function() {
        loadDepartments();
        setupEventListeners();
    });

    // 设置事件监听器
    function setupEventListeners() {
        // 搜索按钮
        document.getElementById('searchBtn').addEventListener('click', function() {
            currentKeyword = document.getElementById('searchInput').value.trim();
            currentPage = 1;
            loadDepartments();
        });

        // 清除搜索按钮
        document.getElementById('clearSearchBtn').addEventListener('click', function() {
            document.getElementById('searchInput').value = '';
            currentKeyword = '';
            currentPage = 1;
            loadDepartments();
        });

        // 搜索输入框回车事件
        document.getElementById('searchInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                currentKeyword = this.value.trim();
                currentPage = 1;
                loadDepartments();
            }
        });

        // 新增按钮
        document.getElementById('addBtn').addEventListener('click', showAddModal);

        // 保存按钮
        document.getElementById('saveBtn').addEventListener('click', saveDepartment);

        // 科室编码检查
        document.getElementById('deptCode').addEventListener('blur', checkDeptCode);

        // 确认删除按钮
        document.getElementById('confirmDeleteBtn').addEventListener('click', confirmDelete);
    }

    // 加载科室数据（分页查询）
    async function loadDepartments() {
        try {
            showLoading();

            if (useMockData) {
                // 使用模拟数据
                setTimeout(() => {
                    const filteredData = filterMockData(mockDepartments);
                    const pagedData = paginateMockData(filteredData);
                    renderTable(pagedData.records);
                    updatePagination(pagedData);
                    updateSearchResultInfo(filteredData.length);
                }, 300);
            } else {
                // 使用真实API
                const url = `http://localhost:8080/api/departments/page?current=${currentPage}&size=${pageSize}&keyword=${encodeURIComponent(currentKeyword)}`;
                const response = await fetch(url);

                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }

                const result = await response.json();
                renderTable(result.records);
                updatePagination(result);
                updateSearchResultInfo(result.total);
            }

        } catch (error) {
            console.error('加载科室数据失败:', error);
            // 如果真实API失败，自动切换到模拟数据
            if (!useMockData) {
                useMockData = true;
                loadDepartments();
            } else {
                showError('加载数据失败，请检查网络连接');
            }
        }
    }

    // 过滤模拟数据 - 修复搜索功能
    function filterMockData(departments) {
        if (!currentKeyword) return departments;

        const keyword = currentKeyword.toLowerCase();
        console.log('搜索关键词:', keyword); // 调试信息

        return departments.filter(dept => {
            const matchCode = dept.deptCode && dept.deptCode.toLowerCase().includes(keyword);
            const matchName = dept.deptName && dept.deptName.toLowerCase().includes(keyword);
            const matchHead = dept.deptHead && dept.deptHead.toLowerCase().includes(keyword);
            const matchLocation = dept.deptLocation && dept.deptLocation.toLowerCase().includes(keyword);

            const isMatch = matchCode || matchName || matchHead || matchLocation;
            console.log(`科室 ${dept.deptName}:`, { matchCode, matchName, matchHead, matchLocation, isMatch }); // 调试信息

            return isMatch;
        });
    }

    // 分页模拟数据
    function paginateMockData(departments) {
        const startIndex = (currentPage - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const records = departments.slice(startIndex, endIndex);

        return {
            records: records,
            total: departments.length,
            pages: Math.ceil(departments.length / pageSize),
            current: currentPage,
            size: pageSize
        };
    }

    // 更新搜索结果显示
    function updateSearchResultInfo(total) {
        const searchResultInfo = document.getElementById('searchResultInfo');
        if (currentKeyword) {
            searchResultInfo.textContent = `搜索"${currentKeyword}"，找到 ${total} 条结果`;
        } else {
            searchResultInfo.textContent = '';
        }
    }

    // 显示加载状态
    function showLoading() {
        const tbody = document.getElementById('departmentTable');
        tbody.innerHTML = `
                <tr>
                    <td colspan="8" class="text-center py-4">
                        <div class="d-flex justify-content-center align-items-center">
                            <div class="spinner-border text-primary me-3" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                            <span>正在加载数据...</span>
                        </div>
                    </td>
                </tr>
            `;
    }

    // 显示错误信息
    function showError(message) {
        const tbody = document.getElementById('departmentTable');
        tbody.innerHTML = `
                <tr>
                    <td colspan="8" class="text-center py-4">
                        <div class="empty-state">
                            <i class="bi bi-exclamation-triangle text-warning"></i>
                            <h5 class="mt-3">数据加载失败</h5>
                            <p class="text-muted">${message}</p>
                            <button class="btn btn-custom-primary mt-2" onclick="loadDepartments()">
                                <i class="bi bi-arrow-clockwise me-1"></i> 重新加载
                            </button>
                        </div>
                    </td>
                </tr>
            `;
    }

    // 渲染表格数据
    function renderTable(departments) {
        const tbody = document.getElementById('departmentTable');
        tbody.innerHTML = '';

        if (departments.length === 0) {
            tbody.innerHTML = `
                    <tr>
                        <td colspan="8" class="text-center py-5">
                            <div class="empty-state">
                                <i class="bi bi-search"></i>
                                <h5 class="mt-3">${currentKeyword ? '未找到匹配的科室' : '暂无数据'}</h5>
                                <p class="text-muted">${currentKeyword ? `没有找到包含"${currentKeyword}"的科室信息` : '没有科室信息，请添加科室'}</p>
                                ${!currentKeyword ? `
                                <button class="btn btn-custom-primary mt-2" onclick="showAddModal()">
                                    <i class="bi bi-plus-circle me-1"></i> 添加科室
                                </button>
                                ` : ''}
                            </div>
                        </td>
                    </tr>
                `;
            return;
        }

        departments.forEach(dept => {
            const statusBadge = dept.status === 1 ?
                '<span class="status-badge status-active"><i class="bi bi-check-circle me-1"></i>启用</span>' :
                '<span class="status-badge status-inactive"><i class="bi bi-x-circle me-1"></i>停用</span>';

            const row = `
                    <tr>
                        <td class="fw-semibold">${escapeHtml(dept.deptCode)}</td>
                        <td>${escapeHtml(dept.deptName)}</td>
                        <td>${escapeHtml(dept.deptHead || '-')}</td>
                        <td>${escapeHtml(dept.deptPhone || '-')}</td>
                        <td>${escapeHtml(dept.deptLocation || '-')}</td>
                        <td>${statusBadge}</td>
                        <td>${dept.sortOrder || 0}</td>
                        <td class="table-actions">
                            <button class="btn btn-sm btn-custom-outline action-btn" onclick="editDepartment(${dept.id})" title="编辑">
                                <i class="bi bi-pencil"></i> 编辑
                            </button>
                            <button class="btn btn-sm btn-custom-outline action-btn text-danger" onclick="showDeleteModal(${dept.id})" title="删除">
                                <i class="bi bi-trash"></i> 删除
                            </button>
                        </td>
                    </tr>
                `;
            tbody.innerHTML += row;
        });
    }

    // 更新分页信息
    function updatePagination(pageInfo) {
        totalRecords = pageInfo.total;
        const start = (currentPage - 1) * pageSize + 1;
        const end = Math.min(currentPage * pageSize, totalRecords);

        document.getElementById('paginationInfo').textContent =
            `显示第 ${start} 到 ${end} 条，共 ${totalRecords} 条记录`;

        renderPagination(pageInfo.pages);
    }

    // 渲染分页控件
    function renderPagination(totalPages) {
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = '';

        // 上一页
        const prevLi = createPaginationItem('上一页', currentPage > 1, () => {
            if (currentPage > 1) {
                currentPage--;
                loadDepartments();
            }
        });
        pagination.appendChild(prevLi);

        // 页码
        for (let i = 1; i <= totalPages; i++) {
            const pageLi = createPaginationItem(i.toString(), true, () => {
                currentPage = i;
                loadDepartments();
            }, i === currentPage);
            pagination.appendChild(pageLi);
        }

        // 下一页
        const nextLi = createPaginationItem('下一页', currentPage < totalPages, () => {
            if (currentPage < totalPages) {
                currentPage++;
                loadDepartments();
            }
        });
        pagination.appendChild(nextLi);
    }

    // 创建分页项目
    function createPaginationItem(text, enabled, onClick, active = false) {
        const li = document.createElement('li');
        li.className = `page-item ${active ? 'active' : ''} ${!enabled ? 'disabled' : ''}`;

        const a = document.createElement('a');
        a.className = 'page-link';
        a.href = '#';
        a.textContent = text;

        if (enabled) {
            a.addEventListener('click', function(e) {
                e.preventDefault();
                onClick();
            });
        }

        li.appendChild(a);
        return li;
    }

    // 显示新增模态框
    function showAddModal() {
        document.getElementById('modalTitle').innerHTML = '<i class="bi bi-building me-2"></i>新增科室';
        document.getElementById('departmentForm').reset();
        document.getElementById('id').value = '';
        document.getElementById('status').value = '1';
        document.getElementById('sortOrder').value = '0';
        document.getElementById('codeCheckResult').textContent = '请输入英文科室编码';
        document.getElementById('codeCheckResult').className = 'form-text text-muted';
        document.getElementById('deptCode').readOnly = false;

        const modal = new bootstrap.Modal(document.getElementById('departmentModal'));
        modal.show();
    }

    // 编辑科室（查询单个科室）
    async function editDepartment(id) {
        try {
            let department;
            if (useMockData) {
                // 从模拟数据中查找
                department = mockDepartments.find(dept => dept.id === id);
                if (!department) {
                    throw new Error('科室不存在');
                }
            } else {
                // 从真实API获取
                const response = await fetch(`http://localhost:8080/api/departments/${id}`);
                if (!response.ok) {
                    throw new Error('获取科室信息失败');
                }
                department = await response.json();
            }

            fillForm(department);

            document.getElementById('modalTitle').innerHTML = '<i class="bi bi-building me-2"></i>编辑科室';
            document.getElementById('codeCheckResult').textContent = '科室编码不可修改';
            document.getElementById('codeCheckResult').className = 'form-text text-muted';
            document.getElementById('deptCode').readOnly = true;

            const modal = new bootstrap.Modal(document.getElementById('departmentModal'));
            modal.show();

        } catch (error) {
            console.error('编辑科室失败:', error);
            alert('获取科室信息失败');
        }
    }

    // 填充表单数据
    function fillForm(department) {
        document.getElementById('id').value = department.id;
        document.getElementById('deptCode').value = department.deptCode;
        document.getElementById('deptName').value = department.deptName;
        document.getElementById('deptHead').value = department.deptHead || '';
        document.getElementById('deptPhone').value = department.deptPhone || '';
        document.getElementById('deptLocation').value = department.deptLocation || '';
        document.getElementById('status').value = department.status || 1;
        document.getElementById('sortOrder').value = department.sortOrder || 0;
        document.getElementById('deptDescription').value = department.deptDescription || '';
    }

    // 检查科室编码是否存在
    async function checkDeptCode() {
        const deptCode = document.getElementById('deptCode').value.trim();
        const id = document.getElementById('id').value;

        if (!deptCode) {
            document.getElementById('codeCheckResult').textContent = '请输入科室编码';
            document.getElementById('codeCheckResult').className = 'form-text text-warning';
            return;
        }

        // 编辑模式下不检查编码重复
        if (id && id !== '') {
            return;
        }

        try {
            let exists = false;
            if (useMockData) {
                // 在模拟数据中检查
                exists = mockDepartments.some(dept => dept.deptCode === deptCode && dept.id !== parseInt(id));
            } else {
                // 从真实API检查
                const response = await fetch(`http://localhost:8080/api/departments/check-code?deptCode=${encodeURIComponent(deptCode)}`);
                exists = await response.json();
            }

            const resultElement = document.getElementById('codeCheckResult');

            if (exists) {
                resultElement.textContent = '❌ 科室编码已存在';
                resultElement.className = 'form-text text-danger';
            } else {
                resultElement.textContent = '✅ 科室编码可用';
                resultElement.className = 'form-text text-success';
            }
        } catch (error) {
            console.error('检查科室编码失败:', error);
            document.getElementById('codeCheckResult').textContent = '检查失败，请重试';
            document.getElementById('codeCheckResult').className = 'form-text text-warning';
        }
    }

    // 保存科室（新增或更新）
    async function saveDepartment() {
        const formData = getFormData();

        if (!validateForm(formData)) {
            return;
        }

        try {
            if (useMockData) {
                // 模拟保存操作
                if (formData.id) {
                    // 更新
                    const index = mockDepartments.findIndex(dept => dept.id === formData.id);
                    if (index !== -1) {
                        mockDepartments[index] = { ...mockDepartments[index], ...formData };
                    }
                } else {
                    // 新增
                    const newId = Math.max(...mockDepartments.map(dept => dept.id)) + 1;
                    const newDept = {
                        ...formData,
                        id: newId,
                        createTime: new Date().toISOString(),
                        updateTime: new Date().toISOString(),
                        isDeleted: 0
                    };
                    mockDepartments.push(newDept);
                }

                const modal = bootstrap.Modal.getInstance(document.getElementById('departmentModal'));
                modal.hide();

                alert(formData.id ? '科室信息更新成功' : '科室创建成功');
                loadDepartments();
            } else {
                // 真实API保存
                const url = formData.id ? `http://localhost:8080/api/departments/${formData.id}` : 'http://localhost:8080/api/departments';
                const method = formData.id ? 'PUT' : 'POST';

                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(formData)
                });

                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(errorText);
                }

                const modal = bootstrap.Modal.getInstance(document.getElementById('departmentModal'));
                modal.hide();

                alert(formData.id ? '科室信息更新成功' : '科室创建成功');
                loadDepartments();
            }

        } catch (error) {
            console.error('保存科室失败:', error);
            alert('操作失败: ' + error.message);
        }
    }

    // 获取表单数据
    function getFormData() {
        return {
            id: document.getElementById('id').value ? parseInt(document.getElementById('id').value) : null,
            deptCode: document.getElementById('deptCode').value.trim(),
            deptName: document.getElementById('deptName').value.trim(),
            deptHead: document.getElementById('deptHead').value.trim(),
            deptPhone: document.getElementById('deptPhone').value.trim(),
            deptLocation: document.getElementById('deptLocation').value.trim(),
            deptDescription: document.getElementById('deptDescription').value.trim(),
            status: parseInt(document.getElementById('status').value),
            sortOrder: parseInt(document.getElementById('sortOrder').value) || 0
        };
    }

    // 验证表单
    function validateForm(data) {
        if (!data.deptCode) {
            alert('请输入科室编码');
            document.getElementById('deptCode').focus();
            return false;
        }

        if (!data.deptName) {
            alert('请输入科室名称');
            document.getElementById('deptName').focus();
            return false;
        }

        return true;
    }

    // 显示删除确认模态框
    function showDeleteModal(id) {
        departmentToDelete = id;
        const modal = new bootstrap.Modal(document.getElementById('deleteModal'));
        modal.show();
    }

    // 确认删除
    async function confirmDelete() {
        if (!departmentToDelete) return;

        try {
            if (useMockData) {
                // 模拟删除
                const index = mockDepartments.findIndex(dept => dept.id === departmentToDelete);
                if (index !== -1) {
                    mockDepartments.splice(index, 1);
                }

                const modal = bootstrap.Modal.getInstance(document.getElementById('deleteModal'));
                modal.hide();

                alert('删除成功');
                loadDepartments();
                departmentToDelete = null;
            } else {
                // 真实API删除
                const response = await fetch(`http://localhost:8080/api/departments/${departmentToDelete}`, {
                    method: 'DELETE'
                });

                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(errorText);
                }

                const modal = bootstrap.Modal.getInstance(document.getElementById('deleteModal'));
                modal.hide();

                alert('删除成功');
                loadDepartments();
                departmentToDelete = null;
            }

        } catch (error) {
            console.error('删除科室失败:', error);
            alert('操作失败: ' + error.message);
        }
    }

    // HTML转义函数
    function escapeHtml(text) {
        if (text === null || text === undefined) return '';
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
</script>
</body>
</html>